<template>
    <div class="box" id="clock">
        <p id="date" class="date">{{ date }}</p>
        <p id="time" class="time">{{ time }}</p>
        <p class="text">数字时钟</p>
    </div>
</template>


<script setup>
import { onBeforeUnmount, onMounted, ref } from 'vue';

// 定义响应式的日期和时间
let week = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
let date = ref('');
let time = ref('');

const updateTime = () => {
    let cd = new Date();
    time.value = zeroPadding(cd.getHours(), 2) + ':' + zeroPadding(cd.getMinutes(), 2) + ':' + zeroPadding(cd.getSeconds(), 2);
    date.value = zeroPadding(cd.getFullYear(), 4) + '-' + zeroPadding(cd.getMonth() + 1, 2) + '-' + zeroPadding(cd.getDate(), 2) + ' ' + week[cd.getDay()];
};

const zeroPadding = (num, digit) => {
    return num.toString().padStart(digit, '0');
};

let timerID = ref(0);

onMounted(() => {
    timerID.value = setInterval(updateTime, 1000); // 每秒更新一次
    updateTime(); // 初始化时调用一次
});

onBeforeUnmount(() => {
    clearInterval(timerID.value); // 组件卸载时清除定时器
});

</script>


<style lang="scss" scoped>
.box {
    border: .1rem solid rgba(0, 0, 0, 0.2);
    border-radius: .5rem;
    overflow: hidden;
    margin-bottom: 1.5rem;
    background: #fff;
}

#clock {
    padding: 2rem;
    font-family: "Share Tech Mono", monospace;
    background: #0f3854;
    background: radial-gradient(ellipse at center, #0a2e38 0%, #000000 70%);
    color: #ffffff;
    text-align: center;
    color: #daf6ff;
    text-shadow: 0 0 1.2rem #0aafe6, 0 0 1.2px rgba(10, 175, 230, 0);
}

#clock .time {
    letter-spacing: 0.1em;
    font-size: 5rem;
    padding: 5px 0;
}

#clock .date {
    letter-spacing: 0.1em;
    font-size: 1.6rem;
}

#clock .text {
    letter-spacing: 0.1em;
    font-size: 1.6rem;
    /* padding: 20px 0 0; */
}
</style>